package com.shawn.integeration.schedule.executor;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.concurrent.CancellationException;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.ThreadFactory;

/**
 * @author shawn
 * @description: 自定义定时调度执行器
 * @date 2024/1/22
 */
public class MyScheduledThreadPoolExecutor extends ScheduledThreadPoolExecutor {
    private Logger log = LoggerFactory.getLogger(MyScheduledThreadPoolExecutor.class);

    public MyScheduledThreadPoolExecutor(int corePoolSize, ThreadFactory factory) {
        super(corePoolSize, factory);
    }

    @Override
    protected void afterExecute(Runnable r, Throwable t) {
        super.afterExecute(r, t);
        // 打印异常信息
        this.printException(r, t);
    }

    public void printException(Runnable r, Throwable t) {
        // 判断 r 是 Future 实例并且已经完成执行的情况下,获取它的执行结果，并检查是否有异常抛出
        if (t == null && r instanceof Future<?>) {
            try {
                Future<?> future = (Future<?>) r;
                if (future.isDone()) {
                    future.get();
                }
            } catch (CancellationException ce) {
                t = ce;
            } catch (ExecutionException ee) {
                t = ee.getCause();
            } catch (InterruptedException ie) {
                Thread.currentThread().interrupt();
            }
        }
        if (t != null) {
            log.error(t.getMessage(), t);
        }
    }
}
